package com.padakeji.android.pworks.app;

import java.lang.reflect.Field;

import com.padakeji.android.pworks.annotation.SaveState;
import com.padakeji.android.pworks.content.JsonWorker;
import com.padakeji.android.pworks.content.JsonWorkerFactory;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;

public class PadaActivity extends AppCompatActivity {

    private View rootView;

    public View getRootView() {
        synchronized (this) {
            if (rootView == null) {
                rootView = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
            }
        }
        return rootView;
    }

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		restoreInstanceState(savedInstanceState);
	}
	
	protected void restoreInstanceState(Bundle savedInstanceState) {
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field f : fields) {
			try {
				SaveState a = f.getAnnotation(SaveState.class);
				if (a != null) {
					
					String fieldName = f.getName();
					String valueJson = savedInstanceState.getString(fieldName);
                    JsonWorker jsonWorker = JsonWorkerFactory.getJsonWorker();
                    Object fieldValue = jsonWorker.fromJson(valueJson, f.getGenericType());
					boolean isAccessible = f.isAccessible();
					f.setAccessible(true);
					f.set(this, fieldValue);
					f.setAccessible(isAccessible);
					
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field f : fields) {
			try {
				SaveState a = f.getAnnotation(SaveState.class);
				if (a != null) {
					
					String fieldName = f.getName();
					boolean isAccessible = f.isAccessible();
					f.setAccessible(true);
					Object fieldValue = f.get(this);
					f.setAccessible(isAccessible);
                    JsonWorker jsonWorker = JsonWorkerFactory.getJsonWorker();
					String valueJson = jsonWorker.toJson(fieldValue);
					outState.putString(fieldName, valueJson);
					
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		super.onSaveInstanceState(outState);
	}
	
}
